package com.jxwifi.cloud.quickcleanserver.chronograph;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.basicactivity.BasicActivity;
import com.idroid.utils.NoDoubleClickListener;
import com.idroid.utils.TextDrawable;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickcleanserver.MainActivity;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.CleaningApplication;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.DetailsBean;
import com.jxwifi.cloud.quickcleanserver.bean.OrderFromBean;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.CountDownProgress;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 计时工作
 * Created by Administrator on 2019/5/14.
 */

public class ChronographActivity extends CleanBasicActivity {

    @Bind(R.id.tv_chro_income_price)
    TextView mTvChroIncomePrice;//收入金额
    @Bind(R.id.tv_form_order_type_text)
    TextView mTvFromOrderTypeText;//服务类型
    @Bind(R.id.tv_chro_order_type)
    TextView mTvChroOrderType;//订单状态
    @Bind(R.id.tv_chro_service_time)
    TextView mTvChroServiceTime;//服务时间
    @Bind(R.id.tv_chro_service_address)
    TextView mTvChroServiceAddress;//地址
    @Bind(R.id.tv_chro_measure_area)
    TextView mTvChroMeasureArea;//面积
    @Bind(R.id.tv_chro_remarks)
    TextView mTvChroRemarks;//备注
    @Bind(R.id.rel_tv_stop_work)
    RelativeLayout mRelTvStopWork;
    @Bind(R.id.tv_chro_return_back)
    TextView mTvChroErturnBack;
    @Bind(R.id.tv_stop_work)
    TextView mTvStopWork;
    @Bind(R.id.lin_tv_chro_remarks)
    LinearLayout mLinTvChroRemarks;

    @Bind(R.id.tv_chronograph_price)
    TextView mTvChronographPrice;//价格
    @Bind(R.id.tv_form_order_code_text)
    TextView mTvFormOrderCodeText;

    @Bind(R.id.circleProgressBar)
    CountDownProgress mCircleProgressBar;
    @Bind(R.id.img_chro_phone_outside)
    TextView mImgChroPhoneOutside;
    @Bind(R.id.sv_chronograph_view)
    ScrollView mSvChrongraphView;
    @Bind(R.id.lin_chro_bottom_work)
    LinearLayout mLinChroBottomWork;

    private String mOrderCode;

    private String mWorkTime = "00:00:00";//工作时间默认为00:00:00
    private String money = "0.0";//默认开始时候的价格
    private long mtimes;//默认开始时候的时间
    private boolean mIssuspend = true;
    private boolean mProgress = true;

    private boolean mIsTimesSetting = true;//控制点击按钮的判断（开始与暂停时间间隔为30秒）
    private CountDownTimer mtime;

    private OrderFromBean morderFromBean;

    private LoadDialog mLoadDialog;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chronograph_work);
        ButterKnife.bind(this);
        openEventBus();
        mLoadDialog = new LoadDialog(mBaseContext);
        initHeadLayout();
        mOrderCode = getIntent().getStringExtra("order_code");
    }

    /**
     * 初始化浸入式标题
     */
    private void initHeadLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @OnClick({R.id.rel_img_back_pressed, R.id.img_chro_phone_outside, R.id.tv_chro_return_back,
            R.id.rel_tv_stop_work})
    void clickCK(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            //返回
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
            //电话
            case R.id.img_chro_phone_outside:
                tellPhone();
                break;
            //回到工作台于工作完成按钮
            case R.id.tv_chro_return_back:
                if (StateUtils.SER_END.equals(morderFromBean.getOrderStatus())||StateUtils.SER_FINISHED.equals(morderFromBean.getOrderStatus())) {
                    CleaningApplication.JUMP_TYPE = 50;
                    intent.setClass(mBaseContext, MainActivity.class);
                    intent.putExtra("mainindex", "1");
                    startActivity(intent);
                } else {
                    if (StateUtils.SER_TIME_STOP.equals(morderFromBean.getOrderStatus())) {
                        Toast toast =Toast.makeText(mBaseContext, "暂停中，不可点击完成", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast,3000);
                        return;
                    } else {
                        final KAlertDialog dialogshow=new KAlertDialog(mBaseContext,"确认是否工作已完成");
                        dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
                            @Override
                            protected void onNoDoubleClick(View v) {

                                workfinsh();
                                dialogshow.dismiss();
                            }
                        });
                        dialogshow.show();
                    }
                }
                break;
            //暂停工作
            case R.id.rel_tv_stop_work:
                if (mIsTimesSetting) {
                    countdownMethod();
                    if (mIssuspend) {
                        mIssuspend = false;
                        initstopTime();
                    } else {
                        mIssuspend = true;
                        timeRestart();
                    }
                } else {
                    Toast toast =Toast.makeText(mBaseContext, "操作过于频繁，请10秒后在操作", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                }
                break;
        }
    }

    public void initView() {
        mSvChrongraphView.setVisibility(View.VISIBLE);
        mLinChroBottomWork.setVisibility(View.VISIBLE);
        if (StateUtils.SER_TIME_START.equals(morderFromBean.getOrderStatus())) {//开始计时
            mTvChroOrderType.setText("已开始");
            mRelTvStopWork.setVisibility(View.VISIBLE);
            mTvChroErturnBack.setText("工作完成");
            mTvStopWork.setText("暂停工作");
            TextDrawable.drawable(mBaseContext, mTvStopWork, R.mipmap.icon_stop, 0);
            mImgChroPhoneOutside.setVisibility(View.VISIBLE);
            mCircleProgressBar.startCountDownTime();
        } else if (StateUtils.SER_TIME_STOP.equals(morderFromBean.getOrderStatus())) {//计时暂停
            mTvChroOrderType.setText("已暂停");
            mRelTvStopWork.setVisibility(View.VISIBLE);
            mTvChroErturnBack.setText("工作完成");
            mTvStopWork.setText("开始工作");
            mImgChroPhoneOutside.setVisibility(View.VISIBLE);
            mIssuspend = false;
            TextDrawable.drawable(mBaseContext, mTvStopWork, R.mipmap.icon_start, 0);
        } else if (StateUtils.SER_TIME_START_RE.equals(morderFromBean.getOrderStatus())) {//计时重新开始
            mTvChroOrderType.setText("已开始");
            mRelTvStopWork.setVisibility(View.VISIBLE);
            mTvChroErturnBack.setText("工作完成");
            mImgChroPhoneOutside.setVisibility(View.VISIBLE);
            mTvStopWork.setText("暂停工作");
            TextDrawable.drawable(mBaseContext, mTvStopWork, R.mipmap.icon_stop, 0);
            mCircleProgressBar.startCountDownTime();
        } else if (StateUtils.SER_FINISHED.equals(morderFromBean.getOrderStatus())) {//保洁员服务完成
            mTvChroOrderType.setText("已结束");
            mRelTvStopWork.setVisibility(View.GONE);
            mTvChroErturnBack.setText("回到工作台");
            mImgChroPhoneOutside.setVisibility(View.GONE);
            //已结束后取实体中的价格和时间显示
            setUpPrice(Double.valueOf(morderFromBean.getTotalAmount()));
        }
        mTvFromOrderTypeText.setText(morderFromBean.getProductName());
        mTvChroServiceTime.setText(morderFromBean.getServiceTime());
        mTvChroServiceAddress.setText(morderFromBean.getProvince() + "" + morderFromBean.getCity() + morderFromBean.getArea() + "" + "" + morderFromBean.getAddress());
        mTvChroMeasureArea.setText(morderFromBean.getAreaSize());
        mTvFormOrderCodeText.setText(morderFromBean.getOrderCode());
        if (TextUtils.isEmpty(morderFromBean.getRemark())) {
            mLinTvChroRemarks.setVisibility(View.GONE);
        } else {
            mLinTvChroRemarks.setVisibility(View.VISIBLE);
            mTvChroRemarks.setText(morderFromBean.getRemark());
        }

        mCircleProgressBar.setAddCountDownListener(new CountDownProgress.OnCountDownFinishListener() {
            @Override
            public void countDownFinished() {
                Log.w("oushuhua", "重复操作");
                initgettime();
            }
        });
    }

    //获取服务总时长和金额
    public void initgettime() {
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", mOrderCode);
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_GETTIME, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    money = obj.getString("money");
                    mtimes = obj.getLong("times");
                    Log.w("oushuhua", "money=" + money + "mtimes" + mtimes);
                    if (mProgress) {
                        if (mtimes > 0) {
                            mCircleProgressBar.setTextDesc(mCircleProgressBar.change((int) mtimes));
                        } else {
                            mCircleProgressBar.setTextDesc(mWorkTime);
                        }
                        mProgress = false;
                    }
                    setUpPrice(Double.valueOf(money));
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initgettime();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }

    //得到实体数据
    public void intidata() {
        if (TextUtils.isEmpty(mOrderCode)){
            return;
        }
        Params params = new Params();
        params.add("orderCode", mOrderCode);
        AuzHttp.get(UrlPool.GET_ORDER_INFO, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                mLoadDialog.dismiss();
                if (code == 0) {
                    DetailsBean mdetailsBean = JSON.parseObject(data, DetailsBean.class);
                    morderFromBean = mdetailsBean.getOrderInfo();
                    initView();
                    initgettime();
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        intidata();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mLoadDialog.dismiss();
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }

    //暂停工作
    public void initstopTime() {
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", morderFromBean.getOrderCode());
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_TIME_STOP, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    mCircleProgressBar.countdownstop();
                    mCircleProgressBar.cleancounttime();
                    mTvStopWork.setText("开始工作");
                    TextDrawable.drawable(mBaseContext, mTvStopWork, R.mipmap.icon_stop, 0);
                    morderFromBean.setOrderStatus(StateUtils.SER_TIME_STOP);//修改实体中的状态为暂停
                    initView();
                    Toast toast =Toast.makeText(mBaseContext, "暂停工作", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initstopTime();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mIssuspend = true;
                mIsTimesSetting = true;
                if (mtime != null)
                    mtime.cancel();
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }

    //重新开始时间
    public void timeRestart() {
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", morderFromBean.getOrderCode());
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_TIME_RESTART, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    money = obj.getString("money");
                    mtimes = obj.getLong("times");
                    mCircleProgressBar.setTextDesc(mCircleProgressBar.change((int) mtimes));
                    setUpPrice(Double.valueOf(money));
                    mCircleProgressBar.countstarts();
                    mTvStopWork.setText("暂停服务");
                    TextDrawable.drawable(mBaseContext, mTvStopWork, R.mipmap.icon_start, 0);
                    morderFromBean.setOrderStatus(StateUtils.SER_TIME_START_RE);//修改实体中的状态为重新开始
                    initView();
                    Toast toast =Toast.makeText(mBaseContext, "计时开始", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        timeRestart();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mIssuspend = false;
                mIsTimesSetting = true;
                if (mtime != null)
                    mtime.cancel();
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }

    //服务完成
    public void workfinsh() {
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", morderFromBean.getOrderCode());
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_FINISH, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    mCircleProgressBar.countdownstop();//计时工具停止
                    mCircleProgressBar.cleancounttime();
                    money = obj.getString("money");
                    mtimes = obj.getLong("times");
                    double doumoney = Double.valueOf(money);
                    double doumtimes = Double.valueOf(mtimes);
                    morderFromBean.setTotalAmount("" + doumoney);
                    morderFromBean.setServiceTimeSecond((long) doumtimes);
                    morderFromBean.setOrderStatus(StateUtils.SER_FINISHED);//实体类状态修改为服务完成
                    initView();
                    Toast toast =Toast.makeText(mBaseContext, "服务完成", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        workfinsh();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }

    //价格中的字体大小处理
    public void setUpPrice(double price) {
        String mStrPrice;
        if (price>Double.valueOf(morderFromBean.getDeposit())){
            mStrPrice = "收入:" + price + "元";
        }else{
            mStrPrice = "收入:" + morderFromBean.getDeposit() + "元";
        }
        SpannableString styledText = new SpannableString(mStrPrice);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style1), 0, mStrPrice.indexOf(":") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), mStrPrice.indexOf(":") + 1, mStrPrice.indexOf("."), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style1), mStrPrice.indexOf(".") + 1, mStrPrice.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvChronographPrice.setText(styledText);
    }

    public void countdownMethod() {
        mIsTimesSetting = false;
        mtime = new CountDownTimer(10 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                mIsTimesSetting = true;
            }
        }.start();
    }

    //虚拟电话号码
    public void tellPhone() {
        Params params = new Params();
        params.add("orderCode", morderFromBean.getOrderCode());
        AuzHttp.get(UrlPool.GET_SECRENO_GENERATE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    if (!TextUtils.isEmpty(data)) {
                        Intent mTelintent = new Intent(Intent.ACTION_DIAL);
                        Uri murldata = Uri.parse("tel:" + data.replace("\\", ""));
                        mTelintent.setData(murldata);
                        startActivity(mTelintent);
                    } else {
                        Toast toast =Toast.makeText(mBaseContext, "电话号码有误请确认", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast,3000);
                    }
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        tellPhone();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCircleProgressBar.atcancel();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLoadDialog.show();
        intidata();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mCircleProgressBar.atcancel();
        mCircleProgressBar.cleancounttime();
        mProgress = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCircleProgressBar.atcancel();
        mCircleProgressBar.cleancounttime();
        mProgress = true;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mCircleProgressBar.atcancel();
        mCircleProgressBar.cleancounttime();
        mProgress = true;
    }


}
